package primetest.impl.dao;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import primetest.dto.RoleDto;
import primetest.impl.dao.RoleDao;
import primetest.impl.dao.Transaction;

//@Stateless
public class RoleDao implements Serializable {
	/**
	 *
	 */
	private static final long serialVersionUID = 3600321397243762670L;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());



	private static List<RoleDto> allItems = null;


	@Inject
	public RoleDao(){
	}


	public List<RoleDto> getAllList(Transaction transaction) throws IOException {
		if (allItems != null) {
			return allItems;
		}
		PreparedStatement prepareStatement = null;
		ResultSet resultSet = null;

		try {

			Connection connection = transaction.getResource(Connection.class);
			prepareStatement = connection.prepareStatement(GET_ALL);
			resultSet = prepareStatement.executeQuery();

			allItems = new ArrayList<RoleDto>();
			while (resultSet.next()) {
				RoleDto roleDto = makeBookDto(transaction, resultSet);
				allItems.add(roleDto);

			}
			return allItems;
		} catch (SQLException e) {
			throw new IOException(e);
		} finally {
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					logger.warn(e.getMessage(), e);
				}
			}

			if (prepareStatement != null) {
				try {
					prepareStatement.close();
				} catch (SQLException e) {
					logger.warn(e.getMessage(), e);
				}
			}
		}
	}

	private RoleDto makeBookDto(Transaction transaction, ResultSet resultSet) throws SQLException, IOException {
		String role = resultSet.getString(1);

		RoleDto roleDto = new RoleDto(role, 0);
		return roleDto;
	}


	public void addRole(Transaction transaction, RoleDto roleDto) throws IOException {
		// TODO Auto-generated method stub

	}


	public void deleteRole(Transaction transaction, String role) throws IOException {
		// TODO Auto-generated method stub

	}

	private static final String GET_ALL = "select role from s_role order by role";

}
